//
// AWS Manager - A free AWS console application demonstrating advanced concepts
// Copyright (C) 2008-2010 Sean O'Dell. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.awsmanager.common;

import com.sun.data.provider.RowKey;
import com.sun.data.provider.impl.ObjectListDataProvider;
import com.sun.webui.jsf.model.Option;
import com.xerox.amazonws.ec2.EC2Exception;
import com.xerox.amazonws.ec2.GroupDescription;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sean ODell
 */
public class EC2SecurityGroupDataProvider extends ObjectListDataProvider {

    private ArrayList ec2SecurityGroupList = new ArrayList();
    private EC2Connection ec2connection;

    public EC2SecurityGroupDataProvider() {
        setList(ec2SecurityGroupList);
        setObjectType(EC2SecurityGroup.class);
    }

    public void load(EC2Connection ec2connection) {

        clearObjectList();
        List<String> params = new ArrayList<String>();
        List<GroupDescription> securitygroups = null;

        if (ec2connection == null) {
            this.ec2connection = null;
            return;
        } else {
            this.ec2connection = ec2connection;
        }

        if ((this.ec2connection = ec2connection) == null) {
            return;
        }

        ArrayList<String> ec2Regions = ec2connection.getEc2RegionNames();
        EC2Region ec2RegionInfo = null;

        for (String ec2Region : ec2Regions) {

            ec2RegionInfo = (EC2Region) ec2connection.getEc2RegionInfo().get(ec2Region);

            try {
                securitygroups = ec2RegionInfo.getRegionConnection().describeSecurityGroups(params);
            } catch (EC2Exception ex) {
                Logger.getLogger(EC2SecurityGroupDataProvider.class.getName()).log(Level.SEVERE, null, ex);
                securitygroups = null;
            }

            if (securitygroups != null) {
                for (GroupDescription securitygroup : securitygroups) {
                    EC2SecurityGroup securitygroupInfo = new EC2SecurityGroup();
                    securitygroupInfo.setRegion(ec2Region);
                    securitygroupInfo.setName(securitygroup.getName());
                    securitygroupInfo.setDescription(securitygroup.getDescription());
                    securitygroupInfo.setowner(securitygroup.getOwner());
                    securitygroupInfo.setpermissions(securitygroup.getPermissions());
                    getList().add(securitygroupInfo);
                }
            }
        }
    }

    public EC2SecurityGroup getSecurityGroup(RowKey rowKey) {
        EC2SecurityGroup ec2SecurityGroup = (EC2SecurityGroup) getObject(rowKey);
        return ec2SecurityGroup;
    }

    public Option[] getSecurityGroupsOptions() {
        int i = 0;
        Option[] securityGroupsAvailableOptions = new Option[ec2SecurityGroupList.size()];

        for (i = 0; i < ec2SecurityGroupList.size(); i++) {
            EC2SecurityGroup ec2SecurityGroup = (EC2SecurityGroup) ec2SecurityGroupList.get(i);
            securityGroupsAvailableOptions[i] = new Option(ec2SecurityGroup.getName());
        }
        return securityGroupsAvailableOptions;
    }

    public Option[] getSecurityGroupsOptions(String region) {
        ArrayList<EC2SecurityGroup> ec2SecurityGroupsRegion = new ArrayList();
        for (int i = 0; i < ec2SecurityGroupList.size(); i++) {
            EC2SecurityGroup ec2SecurityGroup = (EC2SecurityGroup) ec2SecurityGroupList.get(i);
            if (ec2SecurityGroup.getRegion().equals(region)) {
                ec2SecurityGroupsRegion.add(ec2SecurityGroup);
            }
        }
        Option[] securityGroupsAvailableOptions = new Option[ec2SecurityGroupsRegion.size()];
        for (int i = 0; i < ec2SecurityGroupsRegion.size(); i++) {
            EC2SecurityGroup ec2SecurityGroup = (EC2SecurityGroup) ec2SecurityGroupsRegion.get(i);
            securityGroupsAvailableOptions[i] = new Option(ec2SecurityGroup.getName());
        }
        return securityGroupsAvailableOptions;
    }

    public String createSecurityGroup(HashMap securityGroupInfo) {
        String statusMsg = new String();
        String sgName = null;
        String sgDesc = null;
        String sgRegion = null;

        if (ec2connection == null) {
            statusMsg = statusMsg + "Please update user settings first.";
            return statusMsg;
        }

        if (((sgName = (String) securityGroupInfo.get("sgName")) != null) &&
                ((sgDesc = (String) securityGroupInfo.get("sgDesc")) != null) &&
                ((sgRegion = (String) securityGroupInfo.get("sgRegion")) != null)) {

            EC2Region ec2RegionInfo = null;
            ec2RegionInfo = (EC2Region) ec2connection.getEc2RegionInfo().get(sgRegion);

            try {
                ec2RegionInfo.getRegionConnection().createSecurityGroup(sgName, sgDesc);
                statusMsg = statusMsg + "Security Group Created\n";
                statusMsg = statusMsg + "Security Group Region     : " + sgRegion + "\n";
                statusMsg = statusMsg + "Security Group Name       : " + sgName + "\n";
                statusMsg = statusMsg + "Security Group Description: " + sgDesc + "\n";
            } catch (EC2Exception ex) {
                statusMsg = statusMsg + "Error: " + ex + "\n";
                Logger.getLogger(EC2SecurityGroupDataProvider.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return statusMsg;
    }

    public String deleteSecurityGroups(RowKey[] selectedRowKeys) {
        String statusMsg = new String();

        for (int i = 0; i < selectedRowKeys.length; i++) {

            RowKey rowKey = selectedRowKeys[i];
            EC2SecurityGroup ec2SecurityGroup = getSecurityGroup(rowKey);
            EC2Region ec2RegionInfo = null;
            ec2RegionInfo = (EC2Region)
                    ec2connection.getEc2RegionInfo().get(ec2SecurityGroup.getRegion());

            try {
                ec2RegionInfo.getRegionConnection().deleteSecurityGroup(ec2SecurityGroup.getName());
                statusMsg = statusMsg + "Deleted Security Group: " + ec2SecurityGroup.getName() + "\n";
            } catch (EC2Exception ex) {
                statusMsg = statusMsg + "Error: " + ex + "\n";
            }
        }
        return statusMsg;
    }
}
